package models

import (
	"fmt"
	"log"
	"strings"
	"time"

	"GoTime/response"
	. "GoTime/utils"
	"encoding/json"
	"errors"

	"github.com/spf13/cast"
	"xorm.io/builder"
)

type Securityguard struct {
	Id               int       `xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	UserId           int       `xorm:"not null comment('用户id外键关联dts_user中的id') index INT(11)"`
	SchoolId         int       `form:"school_id" xorm:"not null comment('驾校id外键关联dts_school中的自增id') index INT(11)"`
	IcId             int       `xorm:"default 0 comment('IC卡id,安全员可以没有IC卡也可以拥有多张IC卡，当前为生效IC卡id') INT(11)"`
	FingerId         int       `xorm:"default 0 comment('指纹id，安全员可以拥有多个指纹记录，当前为生效指纹id') INT(11)"`
	PortraitId       int       `xorm:"default 0 comment('头像id，安全员可以拥有多个头像记录，当前为生效头像id') INT(11)"`
	LicenceNumber    string    `form:"licence_number" xorm:"default '' comment('驾驶证号') VARCHAR(128)"`
	LicenceGrantDate time.Time `xorm:"comment('驾驶证初领日期 YYYYMMDD') DATE"`
	OccupationNumber string    `form:"occupation_number" xorm:"default '' comment('教练员职业资格证件号') VARCHAR(128)"`
	OccupationRank   string    `form:"occupation_rank" xorm:"default '1' comment('教练员职业资格等级，1：一级，2：二级，3：三级，4：四级') ENUM('1','2','3','4')"`
	DrivingCarType   string    `form:"driving_car_type" xorm:"default 'C1' comment('准驾车型') ENUM('A1','A2','A3','B1','B2','C1','C2','C3','C4','C5','D','E','F','M','N','P')"`
	TeachingCarType  string    `form:"teaching_car_type" xorm:"default 'C1' comment('准教车型') ENUM('A1','A2','A3','B1','B2','C1','C2','C3','C4','C5','D','E','F','M','N','P')"`
	EntryDate        time.Time `xorm:"comment('入职日期 YYYYMMDD') DATE"`
	DepartureDate    time.Time `xorm:"comment('离职日期 YYYYMMDD') DATE"`
	Status           string    `form:"status" xorm:"default '1' comment('0：在职, 1：离职') ENUM('0','1')"`
	ApprovalStatus   string    `xorm:"default '0' comment('安全员提交运管审核状态，0:待审核，1:通过审核，2:未通过审核') ENUM('0','1','2')"`
	RecordStatus     string    `xorm:"not null default '0' comment('备案状态') ENUM('0','1')"`
	InstitutionCode  string    `xorm:"VARCHAR(16)"`
	Remark           string    `xorm:"VARCHAR(255)"`
	Isused           string    `xorm:"default '1' comment('1 在使用  0 已删除') ENUM('0','1')"`
}

func (s *Securityguard) GetSecurityList(filter builder.Cond, pageSize int, offset int) (list []*response.SecurityListResponse, count int64, err error) {
	if err = engine.Table("dts_securityguard").Alias("c").Select("c.id,c.school_id,c.status,c.approval_status,c.record_status,c.teaching_car_type,c.entry_date,c.departure_date,u.name,u.phone,u.sex,u.address,u.id_number,u.id_type,u.district,u.native,u.Nation,u.Nationality,c.licence_number,c.licence_grant_date,c.occupation_number,c.occupation_rank,c.driving_car_type,dp.image_url,dp.institution_code as portrait_code").Join("LEFT", []string{"dts_user", "u"}, "c.user_id=u.id").Join("RIGHT", []string{"dts_portrait", "dp"}, "dp.id=c.portrait_id").Where(" c.isused=?", "1").And(filter).Desc("c.id").Limit(pageSize, offset).Find(&list); err != nil {
		return list, 0, err
	}
	_, err = engine.Table("dts_securityguard").Alias("c").Select("count(c.id) as count").Join("LEFT", []string{"dts_user", "u"}, "c.user_id=u.id").Where("c.isused=?", "1").And(filter).Get(&count)
	if err != nil {
		return list, count, err
	}
	for k, _ := range list {
		list[k].Phone = strings.Replace(list[k].Phone, "s", "", -1)
		list[k].IdNumber = strings.Replace(list[k].IdNumber, "s", "", -1)
	}
	return list, count, nil
}

func (s *Securityguard) GetById(id interface{}) (list *Securityguard, err error) {
	list = new(Securityguard)
	if _, err = engine.Table("dts_securityguard").Where("id = ? and isused=?", id, "1").Get(list); err != nil {
		return list, err
	}
	return list, nil
}

func (s *Securityguard) RecordSecurity(institutionCode string, user *User, photo, fingerCode, province, city, imageUrl string) (err error) {
	var (
		retMap  map[string]interface{}
		url     string
		reqType int64
	)
	data := map[string]interface{}{
		"inscode":         institutionCode,                             //培训机构编号
		"secunum":         s.InstitutionCode,                           //安全员编号
		"name":            user.Name,                                   //姓名
		"sex":             user.Sex,                                    //性别
		"idcard":          strings.Replace(user.IdNumber, "s", "", -1), //身份证号
		"mobile":          strings.Replace(user.Phone, "s", "", -1),    //手机号码
		"address":         user.Address,                                //联系地址
		"photo":           photo,                                       //照片文件ID
		"drilicence":      s.LicenceNumber,                             //驾驶证号
		"occupationno":    s.OccupationNumber,                          //职业资格证号
		"occupationlevel": s.OccupationRank,                            //职业资格等级
		"dripermitted":    s.DrivingCarType,                            //准驾车型
		"teachpermitted":  s.TeachingCarType,                           //准教车型
		"employstatus":    s.Status,                                    //供职状态0:在职1:离职
		"hiredate":        s.EntryDate.Format("20060102"),              //入职日期
	}
	if fingerCode == "" {

	} else {
		data["fingerprint"] = fingerCode
	}
	log.Println(s.LicenceGrantDate.Format("20060102"), ",2222222333333")
	if cast.ToString(s.LicenceGrantDate.Format("20060102")) == "" {

	} else {
		data["fstdrilicdate"] = s.LicenceGrantDate.Format("20060102")
	}
	if s.Status != "0" {
		data["leavedate"] = s.DepartureDate.Format("20060102")
	}
	if city == "130100" {
		reqType = 3
	} else {
		reqType = 2
	}
	if data["photo"], err = FileId(imageUrl, "securityguardimg", reqType, province, city); err != nil {
		return err
	}
	if url, err = GetSignURL("securityguard", data, reqType, province, city); err != nil {
		return err
	}
	param, err := json.Marshal(data)
	if err != nil {
		fmt.Println("json.Marshal failed:", err)
		return
	}
	var api_log ApiLog
	api_log.Url = url
	api_log.Param = string(param)
	api_log.Method = "POST"
	api_log.Time = time.Now()
	//请求运管
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		return err
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()
	fmt.Println(retMap)
	errorcode, _ := cast.ToIntE(retMap["errorcode"])
	if province == "340000" {
		//delete(data, "photo")
		//data["baTime"] = time.Now().Format("2006-01-02 15:04:05")
		//data["photoPath"] = imageUrl
		//if _, err := AnHuiServiceAPIURLRequest("safetyPerBA/add.do", "POST", institutionCode, data); err != nil {
		//	Logfile("safetyPerBA", "log.safetyPerBA/add.do.log")
		//	Logfile(err, "log.safetyPerBA/add.do.log")
		//	logs.ZapLogs.Error(err.Error())
		//}
	}

	if errorcode != 0 && !strings.Contains(retMap["message"].(string), "已经备案") {
		fmt.Println(retMap)
		fmt.Println("!!!!")
		return errors.New(retMap["message"].(string))
	}
	//备案成功后将本地数据库securityguard备案状态修改
	return nil
}
